<template>
  <el-row>
    <el-col :span="24"
            id="headerTitle">
      <p>
        <el-tooltip class="item"
                    effect="dark"
                    content="返回"
                    placement="top">
          <span class="el-icon-back"
                id="backIconStyle"
                style="padding-top: 4px;"
                @click="goBack"></span>
        </el-tooltip>
        &nbsp;&nbsp;{{headerTitle}}
      </p>
    </el-col>
    <el-col :span="24"
            class="container">
      <el-form :model="form"
               :rules="rules"
               label-width="100px"
               ref="form">
        <el-col :span="13"
                v-show="$route.query.headTitle=='查看单位'?true:false">
          <el-form-item label="单位邀请码">
            <span>{{invite_code}}</span>
          </el-form-item>
        </el-col>
        <el-col :span="13"
                v-show="$route.query.headTitle=='查看单位'&&invite_code!=''?true:false">
          <el-form-item label="二维码">
            <div class="div-qrcode">
              <!-- <div id="qrCode"
                   style="width:200px"
                   ref="qrCode"></div> -->
              <img class="qrcode"
                   :src="qrcodeUrl"
                   alt="">
              <el-button type="success"
                         class="success-type"
                         @click="onDownQrcode">下载</el-button>
            </div>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="13">
          <el-form-item label="组织类型"
                        prop="company_org_type">
            <el-radio v-model="form.company_org_type"
                      v-for="(item,i) in optionsType"
                      :key="i"
                      @change="slectLink"
                      :label="item.value">{{item.name}}</el-radio>
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="13">
          <el-form-item label="单位类型"
                        prop="company_type">
            <el-select v-model="form.company_type"
                       :disabled="$route.query.headTitle=='查看单位'?true:false"
                       placeholder="请选择">
              <el-option v-for="item in typeArr"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="13">
          <el-form-item label="业务类型"
                        prop="business_type">
            <el-select v-model="form.business_type"
                       multiple
                       :disabled="$route.query.headTitle=='查看单位'?true:false"
                       placeholder="请选择">
              <el-option v-for="item in businessTypeArr"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="单位名称"
                        prop="company_name">
            <el-input v-model="form.company_name"
                      :disabled="$route.query.headTitle=='查看单位'?true:false"
                      placeholder="请输入单位名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="单位简称"
                        prop="small_name">
            <el-input v-model="form.small_name"
                      :disabled="$route.query.headTitle=='查看单位'?true:false"
                      placeholder="请输入单位简称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="单位地址"
                        v-if="$route.query.headTitle=='创建单位'"
                        prop="area_id">
            <!-- <LocationSelect :locationData="locationData"></LocationSelect> 数据不是最新的，比如‘江干区’现在没有了-->
            <LocationSelect class="normal-input"
                            ref="locationSelect"
                            :locaData.sync="projectInfoForm"></LocationSelect>
          </el-form-item>
          <el-form-item label="单位地址"
                        v-if="$route.query.headTitle=='查看单位'"
                        prop="area_id">
            <el-select v-model="form.province"
                       :disabled="$route.query.headTitle=='查看单位'?true:false"
                       class="col-4"
                       placeholder="请选择">
            </el-select>
            <el-select v-model="form.city"
                       :disabled="$route.query.headTitle=='查看单位'?true:false"
                       class="col-4"
                       placeholder="请选择">
            </el-select>
            <el-select v-model="form.area"
                       :disabled="$route.query.headTitle=='查看单位'?true:false"
                       class="col-4"
                       placeholder="请选择">
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="详细地址"
                        prop="addr">
            <el-input v-model="form.addr"
                      :disabled="$route.query.headTitle=='查看单位'?true:false"
                      placeholder="请输入详细地址"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="13">
          <el-form-item label="具体位置"
                        prop="wd">
            <el-input v-model="projectInfoForm.lonlat"
                      readonly
                      v-if="$route.query.headTitle=='创建单位'"
                      @focus="selectNewMap"
                      placeholder="请选择具体位置"></el-input>
            <el-input v-model="projectInfoForm.lonlat"
                      readonly
                      :disabled="$route.query.headTitle=='查看单位'?true:false"
                      v-else
                      placeholder="请选择具体位置"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24"
                class="bottom-box">
          <el-button @click="onCancel"
                     :disabled="false"> {{$route.query.headTitle=='查看单位'?'返回':'取消'}}</el-button>
          <el-button type="primary"
                     v-if="$route.query.headTitle=='查看单位'?false:true"
                     @click="onSubmit('form')">提交</el-button>
        </el-col>
      </el-form>
      <NewMap :mapLngLat.sync="projectInfoForm"
              :dialogVisible.sync="newmapDialogVisible"></NewMap>
    </el-col>
  </el-row>
</template>

<script>
import QRCode from 'qrcodejs2';
import NewMap from '@/components/Map/NewMap'
import { ProjectListApi } from '@/services/ProjectCenter'
import LocationSelect from '@/components/LocationSelect/LocationSelect'
import { MyCompanyApi } from '@/services/WorkBench';
import { accountApi } from '@/services/CompanySetting'
import { standardCodeApi } from '@/services/StandardCode'
export default {
  components: {
    LocationSelect,
    NewMap
  },
  data () {
    return {
      businessTypeArr: [],
      optionsType: [],
      projectInfoForm: {
        project_name: '',
        nick_name: '',
        business_type: '',
        business_type_list: [],
        major_type: '',
        building_type: '',
        license_number: '',
        assembly_rate: '',
        leader_name: '',
        // leader_phone: '',
        // leader_id: '',
        dept_no: '',
        address: '',
        lon: '',
        lat: '',
        lonlat: '',
        floorage: '',
        status: '',
        contract_total: '',
        sign_time: '',
        application: '',
        img: '',
        img_url: '',
        project_attr: {},
        count: 0,
        project_license_no: '',
        jt_project_id: 0,
        jt_project_name: ''
      },
      newmapDialogVisible: false,
      headerTitle: '',
      typeArr: [],
      // locationData: {},
      invite_code: '',
      form: {
        business_type: [],//业务类型
        addr: '',
        area_id: '',
        small_name: '',
        company_name: '',
        // company_type: '',
        // company_org_type: '',
        jd: '',//经度
        wd: '',//纬度
      },
      projectId: '',
      requestParams: {

      },
      rules: {
        business_type: [
          { required: true, message: '业务类型不能为空', trigger: 'blur' }
        ],
        // company_org_type: [
        //   { required: true, message: '组织类型不能为空', trigger: 'blur' }
        // ],
        // company_type: [
        //   { required: true, message: '单位类型不能为空', trigger: 'blur' }
        // ],
        wd: [
          { required: true, message: '具体位置不能为空', trigger: 'blur' }
        ],
        addr: [
          { required: true, message: '详细地址不能为空', trigger: 'blur' }
        ],
        small_name: [
          { required: true, message: '单位简称不能为空', trigger: 'blur' }
        ],
        company_name: [
          { required: true, message: '单位名称不能为空', trigger: 'blur' }
        ],
        area_id: [
          { required: true, message: '单位地址不能为空', trigger: 'blur' }
        ]
      },
      qrcodeUrl: ''
    }
  },
  methods: {
    // 获取标准码
    standardCode () {
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'companyOrgType'
        }
      }).then((res) => {
        this.optionsType = res.data.list
      }).catch((error) => {
        console.log(error)
      })
    },
    // slectLink (val) {
    //   this.form.company_org_type = val
    // },
    goBack () {
      if (this.$route.query.topPage == '平台里跳转') {
        this.$router.push({ path: '/workbenchMyUnit', query: { topPage: '平台里跳转' } })
      } else {
        this.$router.push({ path: '/workbenchMyUnit' })
      }
    },
    //下载二维码
    onDownQrcode () {
      let a = document.createElement('a')
      a.href = this.qrcodeUrl;
      a.download = '二维码';
      a.click()
      this.$message({
        message: "正在进行下载保存",
        type: 'success'
      })
    },
    bindQRCode () {//生成二维码
      let userInfo = window.localStorage.getItem('userInfo') || '{}'
      userInfo = JSON.parse(userInfo)
      accountApi.getQrcode({
        data: {
          node_type: 1,//组织类型，如果是项目中的部门二维码，则此处传值为4
          id: this.$route.query.org_id,//id，node_type为1时，此处为组织的id，node_type为2时，此处为部门的id，node_type为4时，此处为项目的id，

        }
      }).then(res => {
        let a = document.createElement("a");
        let blob = new Blob([res], { type: 'image/png' })
        let url = URL.createObjectURL(blob)
        this.qrcodeUrl = url
      })
    },
    selectNewMap () {
      this.newmapDialogVisible = true
    },
    //取消
    onCancel () {
      this.invite_code = ''
      this.form = this.$options.data().form;
      this.$refs.form.resetFields()
      this.goBack();
    },
    getBusinessType () {//业务类型
      return standardCodeApi.getStandardCodeData({
        data: {
          code_type: 'businessType'
        }
      }).then((res) => {
        if (res.data) {
          this.businessTypeArr = res.data.list;
          window.localStorage.setItem('businessTypeArr', JSON.stringify(this.businessTypeArr))
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    //提交
    onSubmit (data) {
      this.$refs[data].validate((valid) => {
        if (valid) {
          let obj = Object.assign({}, this.form)
          obj.business_types = obj.business_type.join(',')
          this.$delete(obj, 'business_type')
          MyCompanyApi.createComp({
            data: obj
          }).then((res) => {
            if (res.code == 0) {
              this.$store.state.hasTheUnitIncreaStatus = 1;
              this.$message.success('操作成功!鼠标放在您已创建的单位上可以对该单位进行相应的操作')
              this.onCancel();//取消
            } else {
              this.$store.state.hasTheUnitIncreaStatus = 0;
            }
          }).catch((error) => {
            console.log(error)
          })

        } else {
          console.log('error')
        }
      })
    },
    getComType () {//单位类型
      return MyCompanyApi.getComType({
        params: {
          code_type: 'companyType',
          is_page: 0
        }
      }).then((res) => {
        this.typeArr = res.data.list;
      }).catch((error) => {
        console.log(error)
      })
    },

    getBusinessTypeFunc (arr) {//业务类型    
      let arrV = [];
      if (arr.length > 0) {
        arr.map((item) => {
          arrV.push(item.business_type);//业务类型
        })
      };
      return arrV;
    },
    lookComp () {//查看单位
      MyCompanyApi.lookComp({
        params: {
          org_id: this.$route.query.org_id
        }
      }).then((res) => {
        this.form = res.data;
        let businessType = res.data.business_type_list;
        this.form.business_type = this.getBusinessTypeFunc(businessType);//业务类型
        this.invite_code = res.data.invite_code;
        this.$set(this.projectInfoForm, 'lonlat', res.data.jd + '-' + res.data.wd);
        this.$nextTick(() => {
          this.bindQRCode();//生成二维码
        });
      }).catch((error) => {
        console.log(error)
      })
    }
  },
  watch: {
    projectInfoForm: {
      handler (newval, oldval) {
        this.form.jd = newval.lon;//经度
        this.form.wd = newval.lat;//纬度
        this.form.area_id = newval.area_id;
        console.log('测试88888888888newval=', newval);
      },
      deep: true
    },
    getProjectInfo (newVal, oldVal) {
      this.projectId = Number(newVal);
    },
  },
  computed: {
    getProjectInfo () {
      let stateArray = this.$store.state.projectIdList
      let localArray = JSON.parse(window.localStorage.getItem('projectIdList'))
      let projectArray = !stateArray ? localArray : stateArray
      this.requestParams.project_id = projectArray.join(',')
      return this.requestParams.project_id
    }
  },
  mounted () {
    if (this.$route.query.headTitle == '查看单位') {
      this.lookComp();//查看单位
    }
    // if (this.$route.query.headTitle == '查看单位') {
    //   this.$nextTick(() => {
    //     this.bindQRCode();
    //   })
    // }

  },
  async created () {
    let businessTypeAr = JSON.parse(window.localStorage.getItem('businessTypeArr'));
    if (businessTypeAr) {//业务类型
      this.businessTypeArr = businessTypeAr;
    } else {
      await this.getBusinessType();//业务范围
    }
    await this.standardCode()

    // await this.getComType();//单位类型
    this.headerTitle = this.$route.query.headTitle;
    let store = this.$store.state.projectIdList
    let storage = window.localStorage.getItem('projectIdList') || '[]'
    let projectIdList = []
    projectIdList = store.length > 0 ? store : JSON.parse(storage)
    let id = projectIdList || [1]
    this.projectId = Number(id.join(','));//获取项目主键值
  }
}
</script>

<style lang="scss" scoped>
.col-4 {
  width: 33% !important;
}
.qrcode {
  width: 200px;
  height: 200px;
}
.success-type {
  margin-left: 20px;
  height: 40px;
}
.bottom-box {
  text-align: center;
  margin-top: 20px;
}
.container {
  padding: 20px;
  display: flex;
  flex-direction: column;
}
#headerTitle p {
  padding-bottom: 20px;
  margin-bottom: 20px;
  padding-left: 20px;
  margin-top: 20px;
  border-bottom: 1px solid #d9d9d9;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  padding-right: 20px;
}
.div-qrcode {
  display: flex;
  flex-direction: row;
  align-items: flex-end;
}
</style>